<template>
  <section class="grid-wrapper">
    <h1 class="title">{{ title }}</h1>

    <div v-if="loading" class="msg">Loading products…</div>
    <div v-else-if="error" class="msg error">⚠️ {{ error }}</div>
    <div v-else-if="products.length === 0" class="msg">No products found.</div>

    <div v-else class="grid">
      <ProductCard
        v-for="p in products"
        :key="p.id"
        v-bind="p"
      />
    </div>
  </section>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import ProductCard from './example.vue';

interface Product {
  id: number;
  name: string;
  price: number;
  image: string;
}

const props = withDefaults(defineProps<{ title?: string }>(), { title: 'Products' });

const products = ref<Product[]>([]);
const loading  = ref(true);
const error    = ref('');

onMounted(async () => {
  try {
    const res = await fetch('/api/products').then(r => r.json());
    products.value = res as Product[];
  } catch (e: any) {
    error.value = e.message || 'Network error';
  } finally {
    loading.value = false;
  }
});
</script>

<style lang="scss" scoped>
.grid-wrapper { padding: 2rem; font-family: system-ui, sans-serif; }
.title { margin-top: 0; }
.msg { color: #6b7280; margin-bottom: 1rem; }
.error { color: #ef4444; }
.grid {
  display: grid;
  gap: 1.5rem;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
}
</style>